/**
 * 卖家管理系统 - 仪表盘页面逻辑
 */

class SellerDashboard {
    constructor() {
        this.currentUser = null;
        this.init();
    }

    init() {
        this.checkAuth();
        this.bindEvents();
        this.loadDashboardData();
    }

    // 检查用户认证状态
    checkAuth() {
        const user = JSON.parse(localStorage.getItem('currentUser'));
        console.log('当前用户:', user);
        
        if (!user || user.user_type !== 'Seller') {
            console.log('用户未登录或不是卖家，跳转到首页');
            window.location.href = 'index.html';
            return;
        }
        this.currentUser = user;
        document.getElementById('userName').textContent = user.username;
        console.log('卖家认证成功:', user.username);
    }

    // 绑定事件
    bindEvents() {
        // 用户菜单
        const userMenuBtn = document.getElementById('userMenuBtn');
        const userDropdown = document.getElementById('userDropdown');
        
        userMenuBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            userDropdown.classList.toggle('show');
        });

        document.addEventListener('click', () => {
            userDropdown.classList.remove('show');
        });

        // 退出登录
        document.getElementById('logoutBtn').addEventListener('click', () => {
            this.logout();
        });

        // 快速操作按钮
        document.getElementById('addProductBtn').addEventListener('click', () => {
            this.showAddProductModal();
        });

        document.getElementById('viewOrdersBtn').addEventListener('click', () => {
            window.location.href = 'seller-orders.html';
        });

        document.getElementById('updateShopBtn').addEventListener('click', () => {
            this.showUpdateShopModal();
        });

        document.getElementById('viewAnalyticsBtn').addEventListener('click', () => {
            window.location.href = 'seller-analytics.html';
        });

        // 模态框事件
        this.bindModalEvents();
    }

    // 绑定模态框事件
    bindModalEvents() {
        // 添加商品模态框
        const addProductModal = document.getElementById('addProductModal');
        const closeAddProductModal = document.getElementById('closeAddProductModal');
        const cancelAddProduct = document.getElementById('cancelAddProduct');
        const addProductForm = document.getElementById('addProductForm');

        closeAddProductModal.addEventListener('click', () => {
            this.hideAddProductModal();
        });

        cancelAddProduct.addEventListener('click', () => {
            this.hideAddProductModal();
        });

        addProductForm.addEventListener('submit', (e) => {
            e.preventDefault();
            this.addProduct();
        });

        // 图片预览
        document.getElementById('productImage').addEventListener('change', (e) => {
            this.previewImage(e.target, 'imagePreview');
        });

        // 更新店铺模态框
        const updateShopModal = document.getElementById('updateShopModal');
        const closeUpdateShopModal = document.getElementById('closeUpdateShopModal');
        const cancelUpdateShop = document.getElementById('cancelUpdateShop');
        const updateShopForm = document.getElementById('updateShopForm');

        closeUpdateShopModal.addEventListener('click', () => {
            this.hideUpdateShopModal();
        });

        cancelUpdateShop.addEventListener('click', () => {
            this.hideUpdateShopModal();
        });

        updateShopForm.addEventListener('submit', (e) => {
            e.preventDefault();
            this.updateShop();
        });

        // Logo预览
        document.getElementById('shopLogo').addEventListener('change', (e) => {
            this.previewImage(e.target, 'logoPreview');
        });

        // 点击模态框外部关闭
        addProductModal.addEventListener('click', (e) => {
            if (e.target === addProductModal) {
                this.hideAddProductModal();
            }
        });

        updateShopModal.addEventListener('click', (e) => {
            if (e.target === updateShopModal) {
                this.hideUpdateShopModal();
            }
        });
    }

    // 加载仪表盘数据
    async loadDashboardData() {
        try {
            this.showLoading();
            
            // 加载统计数据
            await this.loadStats();
            
            // 加载最近订单
            await this.loadRecentOrders();
            
            // 加载商品列表
            await this.loadProducts();
            
        } catch (error) {
            console.error('加载仪表盘数据失败:', error);
            this.showToast('加载数据失败', 'error');
        } finally {
            this.hideLoading();
        }
    }

    // 加载统计数据
    async loadStats() {
        try {
            console.log('开始加载统计数据，用户名:', this.currentUser.username);
            const res = await api.getSellerStats(this.currentUser.username);
            console.log('统计数据响应:', res);
            
            if (!res.success) throw new Error(res.error || '获取统计失败');

            const stats = res.data;
            document.getElementById('totalProducts').textContent = stats.total_products || 0;
            document.getElementById('totalOrders').textContent = stats.total_orders || 0;
            document.getElementById('totalRevenue').textContent = `¥${(stats.total_revenue || 0).toFixed(2)}`;
            document.getElementById('avgRating').textContent = (stats.avg_rating || 0).toFixed(1);

        } catch (error) {
            console.error('加载统计数据失败:', error);
            this.showToast('加载统计数据失败: ' + error.message, 'error');
        }
    }

    // 加载最近订单
    async loadRecentOrders() {
        try {
            const ordersTable = document.getElementById('recentOrdersTable');
            
            // 模拟订单数据
            const orders = [
                {
                    orderNumber: 'ORD20241201001',
                    customer: '张**',
                    product: '优质苹果',
                    amount: 89.00,
                    status: 'Processing'
                },
                {
                    orderNumber: 'ORD20241201002',
                    customer: '李**',
                    product: '新鲜橙子',
                    amount: 65.00,
                    status: 'Shipped'
                },
                {
                    orderNumber: 'ORD20241201003',
                    customer: '王**',
                    product: '有机蔬菜',
                    amount: 45.00,
                    status: 'Delivered'
                }
            ];

            if (orders.length === 0) {
                ordersTable.innerHTML = '<tr><td colspan="6" class="no-data">暂无订单数据</td></tr>';
                return;
            }

            ordersTable.innerHTML = orders.map(order => `
                <tr>
                    <td>${order.orderNumber}</td>
                    <td>${order.customer}</td>
                    <td>${order.product}</td>
                    <td>¥${order.amount.toFixed(2)}</td>
                    <td><span class="status status-${order.status.toLowerCase()}">${this.getStatusText(order.status)}</span></td>
                    <td>
                        <button class="btn btn-sm btn-primary" onclick="sellerDashboard.viewOrder('${order.orderNumber}')">
                            查看详情
                        </button>
                    </td>
                </tr>
            `).join('');

        } catch (error) {
            console.error('加载最近订单失败:', error);
        }
    }

    // 加载商品列表
    async loadProducts() {
        try {
            const productsGrid = document.getElementById('productsGrid');

            const res = await api.getSellerProducts(this.currentUser.username);
            if (!res.success) throw new Error(res.error || '获取商品失败');
            const products = res.data.products || [];

            if (products.length === 0) {
                productsGrid.innerHTML = `
                    <div class="no-data">
                        <i class="fas fa-box"></i>
                        <p>暂无商品，点击上方按钮添加商品</p>
                    </div>
                `;
                return;
            }

            productsGrid.innerHTML = products.map(product => `
                <div class="product-card">
                    <div class="product-image">
                        <img src="${product.image || 'https://via.placeholder.com/200x150?text=商品'}" alt="${product.name}">
                    </div>
                    <div class="product-info">
                        <h3>${product.name}</h3>
                        <p class="product-price">¥${Number(product.price).toFixed(2)}</p>
                        <p class="product-stock">库存: ${product.stock ?? 0}</p>
                        <div class="product-actions">
                            <button class="btn btn-sm btn-primary" onclick="sellerDashboard.editProduct('${product.id}')">
                                <i class="fas fa-edit"></i>
                                编辑
                            </button>
                            <button class="btn btn-sm btn-danger" onclick="sellerDashboard.deleteProduct('${product.id}')">
                                <i class="fas fa-trash"></i>
                                删除
                            </button>
                        </div>
                    </div>
                </div>
            `).join('');

        } catch (error) {
            console.error('加载商品列表失败:', error);
        }
    }

    // 显示添加商品模态框
    showAddProductModal() {
        document.getElementById('addProductModal').classList.add('show');
        document.body.style.overflow = 'hidden';
    }

    // 隐藏添加商品模态框
    hideAddProductModal() {
        document.getElementById('addProductModal').classList.remove('show');
        document.body.style.overflow = '';
        document.getElementById('addProductForm').reset();
        document.getElementById('imagePreview').innerHTML = '';
    }

    // 显示更新店铺模态框
    showUpdateShopModal() {
        document.getElementById('updateShopModal').classList.add('show');
        document.body.style.overflow = 'hidden';
        
        // 加载当前店铺信息
        this.loadShopInfo();
    }

    // 隐藏更新店铺模态框
    hideUpdateShopModal() {
        document.getElementById('updateShopModal').classList.remove('show');
        document.body.style.overflow = '';
        document.getElementById('updateShopForm').reset();
        document.getElementById('logoPreview').innerHTML = '';
    }

    // 加载店铺信息
    async loadShopInfo() {
        try {
            const res = await api.getSellerShop(this.currentUser.username);
            if (res.success) {
                const shop = res.data;
                document.getElementById('shopName').value = shop.name || '';
                document.getElementById('shopDescription').value = shop.description || '';
                document.getElementById('shopAddress').value = shop.address || '';
                document.getElementById('shopPhone').value = shop.phone || '';
            }
        } catch (e) {
            console.warn('获取店铺信息失败:', e);
        }
    }

    // 添加商品
    async addProduct() {
        try {
            const formData = new FormData(document.getElementById('addProductForm'));
            
            // 验证表单
            if (!this.validateProductForm(formData)) {
                return;
            }

            this.showLoading();

            const payload = {
                username: this.currentUser.username,
                name: formData.get('name'),
                price: Number(formData.get('price')),
                category: formData.get('category'),
                location: formData.get('location'),
                stock: Number(formData.get('stock')),
                description: formData.get('description') || ''
            };

            const res = await api.addProduct(payload);
            if (!res.success) throw new Error(res.error || '添加失败');

            this.showToast('商品添加成功！', 'success');
            this.hideAddProductModal();
            this.loadProducts(); // 重新加载商品列表

        } catch (error) {
            console.error('添加商品失败:', error);
            this.showToast('添加商品失败', 'error');
        } finally {
            this.hideLoading();
        }
    }

    // 更新店铺信息
    async updateShop() {
        try {
            const formData = new FormData(document.getElementById('updateShopForm'));
            
            // 验证表单
            if (!this.validateShopForm(formData)) {
                return;
            }

            this.showLoading();

            const payload = {
                username: this.currentUser.username,
                name: formData.get('name'),
                description: formData.get('description') || '',
                address: formData.get('address') || '',
                phone: formData.get('phone') || ''
            };

            const res = await api.updateSellerShop(payload);
            if (!res.success) throw new Error(res.error || '更新失败');

            this.showToast('店铺信息更新成功！', 'success');
            this.hideUpdateShopModal();

        } catch (error) {
            console.error('更新店铺信息失败:', error);
            this.showToast('更新店铺信息失败', 'error');
        } finally {
            this.hideLoading();
        }
    }

    // 验证商品表单
    validateProductForm(formData) {
        const name = formData.get('name');
        const price = formData.get('price');
        const category = formData.get('category');
        const location = formData.get('location');
        const stock = formData.get('stock');

        if (!name || !price || !category || !location || !stock) {
            this.showToast('请填写所有必填字段', 'error');
            return false;
        }

        if (parseFloat(price) <= 0) {
            this.showToast('价格必须大于0', 'error');
            return false;
        }

        if (parseInt(stock) < 0) {
            this.showToast('库存不能为负数', 'error');
            return false;
        }

        return true;
    }

    // 验证店铺表单
    validateShopForm(formData) {
        const name = formData.get('name');

        if (!name) {
            this.showToast('店铺名称不能为空', 'error');
            return false;
        }

        return true;
    }

    // 预览图片
    previewImage(input, previewId) {
        const file = input.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = (e) => {
                document.getElementById(previewId).innerHTML = `
                    <img src="${e.target.result}" alt="预览图片" style="max-width: 200px; max-height: 150px; margin-top: 10px;">
                `;
            };
            reader.readAsDataURL(file);
        }
    }

    // 编辑商品
    editProduct(productId) {
        this.showToast('编辑功能开发中...', 'info');
    }

    // 删除商品
    async deleteProduct(productId) {
        if (!confirm('确定要删除这个商品吗？')) {
            return;
        }

        try {
            this.showLoading();

            const res = await api.deleteProduct(productId, this.currentUser.username);
            if (!res.success) throw new Error(res.error || '删除失败');

            this.showToast('商品删除成功！', 'success');
            this.loadProducts(); // 重新加载商品列表

        } catch (error) {
            console.error('删除商品失败:', error);
            this.showToast('删除商品失败', 'error');
        } finally {
            this.hideLoading();
        }
    }

    // 查看订单详情
    viewOrder(orderNumber) {
        this.showToast(`查看订单 ${orderNumber}`, 'info');
        // 这里可以跳转到订单详情页面
    }

    // 获取状态文本
    getStatusText(status) {
        const statusMap = {
            'Pending': '待处理',
            'Processing': '处理中',
            'Shipped': '已发货',
            'Delivered': '已送达',
            'Cancelled': '已取消'
        };
        return statusMap[status] || status;
    }

    // 退出登录
    logout() {
        localStorage.removeItem('currentUser');
        window.location.href = 'index.html';
    }

    // 显示加载状态
    showLoading() {
        document.getElementById('loading').classList.add('show');
    }

    // 隐藏加载状态
    hideLoading() {
        document.getElementById('loading').classList.remove('show');
    }

    // 显示消息提示
    showToast(message, type = 'info') {
        const toast = document.getElementById('toast');
        toast.textContent = message;
        toast.className = `toast toast-${type} show`;
        
        setTimeout(() => {
            toast.classList.remove('show');
        }, 3000);
    }
}

// 初始化卖家仪表盘
const sellerDashboard = new SellerDashboard();
